﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Text;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;

namespace VPLink2013.Webpart
{
    [ToolboxItemAttribute(false)]
    public class Collaborateurs : WebpartVPLink
    {
        StringBuilder sbLogins = new StringBuilder();

        #region get HTML
        /// <summary>
        /// Returns the HTML code rendered by this web part
        /// </summary>
        /// <returns>HTL code as string</returns>
        protected override string GetHtml()
        {
            string strHtml = string.Empty;
            ContextTrace.PrefixFileName = "webpart Collaborateurs";

            string strHtmlFileCache = pathCache + @"\Collaborateurs\Collaborateurs.htm";

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    FileSerialization.CheckFileCacheExists(strHtmlFileCache, 5);
                    if (System.IO.File.Exists(strHtmlFileCache))
                    {
                        strHtml = System.IO.File.ReadAllText(strHtmlFileCache);
                        ContextTrace.AddTrace("File cache found !");
                    }
                    else
                    {
                        global = new GlobalVPLink2013();
                        global.ListeIlsArrivent = new List<Collaborateur>();
                        global.ListeIlsBougent = new List<Collaborateur>();
                        global.ListeIlsPartent = new List<Collaborateur>();
                        global.ListeOffresInternes = new List<OffreInterne>();

                        string strUrl = SPContext.Current.Site.Url;
                        ContextTrace.AddTrace("strUrl : " + strUrl);
                        using (SPSite site = new SPSite(strUrl))
                        {
                            using (SPWeb web = site.RootWeb)
                            {
                                string strList = string.Empty;
                                try
                                {
                                    SPList lst = web.Lists.TryGetList(ListTitles.IlsArriventTitle);
                                    if (lst != null)
                                    {
                                        ProcessCollaborateurs(lst, global.ListeIlsArrivent);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ContextTrace.AddTrace("Exception lors de l'acces à  la liste Ils arrivent");
                                    ContextTrace.AddTrace(ex.StackTrace);
                                }
                                try
                                {
                                    SPList lst = web.Lists.TryGetList(ListTitles.IlsBougentTitle);
                                    if (lst != null)
                                    {
                                        ProcessCollaborateurs(lst, global.ListeIlsBougent);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ContextTrace.AddTrace("Exception lors de l'acces à  la liste Ils bougent");
                                    ContextTrace.AddTrace(ex.StackTrace);
                                }
                                try
                                {
                                    SPList lst = web.Lists.TryGetList(ListTitles.OffresInternesTitle);
                                    if (lst != null)
                                    {
                                        ProcessOffresInternes( lst, global.ListeOffresInternes );
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ContextTrace.AddTrace("Exception lors de l'acces à  la liste Offres Internes");
                                    ContextTrace.AddTrace(ex.StackTrace);
                                }
                                try
                                {
                                    SPList lst = web.Lists.TryGetList(ListTitles.IlsPartentTitle);
                                    if (lst != null)
                                    {
                                        ProcessCollaborateurs(lst, global.ListeIlsPartent);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ContextTrace.AddTrace("Exception lors de l'acces à  la liste Ils partent");
                                    ContextTrace.AddTrace(ex.StackTrace);
                                }
                                //ProcessNomUtilisateur();
                            }
                        }

                        string strXml = FileSerialization.CreateXmlStringFromObj(global);

                        string strXslPath = pathVP + @"\XSL\Collaborateurs\Collaborateurs.xsl";
                        ContextTrace.AddTrace("GetHtml.strXslPath = " + strXslPath);
                        string login = VPLink2013XsltTransformHelper.StringAfter(this.Context.User.Identity.Name);
                        strHtml = VPLink2013XsltTransformHelper.GetTransform(strXml, strXslPath, login, pathTemp);
                        FileSerialization.TraceFile(strHtmlFileCache, strHtml);
                    }
                });
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Erreur GetHtml : " + exc.Message + "/" + exc.StackTrace);
            }
            return strHtml;
        }
        #endregion get HTML

        private void ProcessNomUtilisateur()
        {
            if (sbLogins.Length == 0)
            {
                return;
            }
            string strSql = "SELECT LoginUser, UserName FROM Users WHERE LoginUser IN (" + sbLogins.ToString() + ")";
            SqlConnection conn = VPLink2013SqlHelper.GetConnection(connectionString);
            SqlCommand command = VPLink2013SqlHelper.GetCommand(conn, strSql);
            SqlDataReader Reader = command.ExecuteReader();
            while (Reader.Read())
            {
                string strLogin = VPLink2013SqlHelper.GetValueReader(Reader, 0).ToLower();
                string strNom = VPLink2013SqlHelper.GetValueReader(Reader, 1);
                ContextTrace.AddTrace("strLogin : " + strLogin + "/ strNom : " + strNom);

                foreach (Collaborateur coll in global.ListeIlsArrivent)
                {
                    if (coll.Login == strLogin)
                    {
                        coll.Nom = strNom;
                        ContextTrace.AddTrace("ListeIlsArrivent.strLogin : " + strLogin + "/ strNom : " + strNom);
                    }
                }
                foreach (Collaborateur coll in global.ListeIlsBougent)
                {
                    if (coll.Login == strLogin)
                    {
                        coll.Nom = strNom;
                        ContextTrace.AddTrace("ListeIlsBougent.strLogin : " + strLogin + "/ strNom : " + strNom);
                    }
                }
            }
            VPLink2013SqlHelper.CloseReader(conn, Reader);
        }

        private void ProcessOffresInternes( SPList lst, List<OffreInterne> offresInternes )
        {
            SPQuery spQuery = new SPQuery();
            StringBuilder sb = new StringBuilder();
            SPFieldText lieuTravailTxtField = lst.Fields[OffreInterneFields.LieuField] as SPFieldText;
            SPFieldDateTime dateCreaTxtField = lst.Fields[OffreInterneFields.DateField] as SPFieldDateTime;
            SPFieldText RefTxtField = lst.Fields[OffreInterneFields.RefField] as SPFieldText;
            SPFieldText IntituleInterneTxtField = lst.Fields[OffreInterneFields.IntituleInternePosteField] as SPFieldText;
            SPFieldText IntituleExterneTxtField = lst.Fields[OffreInterneFields.IntituleExternePosteField] as SPFieldText;
            sb.AppendFormat( string.Format( @"<FieldRef Name='{0}' />", lieuTravailTxtField.InternalName ) );
            sb.AppendFormat( string.Format( @"<FieldRef Name='{0}' />", dateCreaTxtField.InternalName ) );
            sb.AppendFormat( string.Format( @"<FieldRef Name='{0}' />", RefTxtField.InternalName ) );
            sb.AppendFormat( string.Format( @"<FieldRef Name='{0}' />", IntituleInterneTxtField.InternalName ) );
            sb.AppendFormat( string.Format( @"<FieldRef Name='{0}' />", IntituleExterneTxtField.InternalName ) );
            spQuery.ViewFields = sb.ToString();
            SPListItemCollection items = lst.GetItems( spQuery );
            foreach( SPListItem item in items )
            {
                offresInternes.Add( new OffreInterne(){
                    DatePublication = VPLink2013SPHelper.GetValueDate(item, OffreInterneFields.DateField),
                    IntituleExterne = VPLink2013SPHelper.GetValue(item, OffreInterneFields.IntituleExternePosteField),
                    IntituleInterne = VPLink2013SPHelper.GetValue(item, OffreInterneFields.IntituleInternePosteField),
                    Localisation = VPLink2013SPHelper.GetValue(item, OffreInterneFields.LieuField),
                    OffreRef = VPLink2013SPHelper.GetValue(item, OffreInterneFields.RefField),
                    OffreUrl = string.Format( @"/Pages/OffresInternes.aspx?offre={0}", item.ID )
                } );
            }
        }

        private void ProcessCollaborateurs(SPList lst, List<Collaborateur> collaborateurs)
        {
            string strListe = lst.Title;
            SPQuery spQuery = new SPQuery();
            StringBuilder sb = new StringBuilder();
            if (strListe.Equals(ListTitles.IlsArriventTitle, StringComparison.CurrentCultureIgnoreCase))
            {
                sb.Append("<Where>");
                sb.Append("<Eq><FieldRef Name='En_x0020_attente'/><Value Type='Boolean'>True</Value></Eq>");
                sb.Append("</Where>");
                sb.Append("<OrderBy><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>");
            }
            if (strListe.Equals(ListTitles.IlsBougentTitle, StringComparison.CurrentCultureIgnoreCase))
            {
                sb.Append("<OrderBy><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>");
            }
            if (strListe.Equals(ListTitles.IlsPartentTitle, StringComparison.CurrentCultureIgnoreCase))
            {
                sb.Append("<Where>");
                sb.Append("<Eq><FieldRef Name='Visible'/><Value Type='Text'>Oui</Value></Eq>");
                sb.Append("</Where>");
                sb.Append("<OrderBy><FieldRef Name='Date_x0020_publication' Ascending='FALSE'/></OrderBy>");
            }
            spQuery.Query = sb.ToString();
            ContextTrace.AddTrace("spQuery.Query : " + spQuery.Query);

            SPListItemCollection items = lst.GetItems(spQuery);
            string strGroupe = string.Empty;
            foreach (SPListItem item in items)
            {
                ContextTrace.AddTrace("-------------------------------");

                Collaborateur coll = new Collaborateur();
                if (strListe.Equals(ListTitles.IlsArriventTitle, StringComparison.CurrentCultureIgnoreCase)
                    || strListe.Equals(ListTitles.IlsBougentTitle, StringComparison.CurrentCultureIgnoreCase))
                {
                    coll.Photo = item.GetItemListFieldValueAsUrlValue(Fields.PhotoField);

                    if (string.IsNullOrEmpty(coll.Photo))
                    {
                        break;
                    }

                    int iPos = coll.Photo.LastIndexOf("/");
                    if (iPos <= 0)
                    {
                        break;
                    }
                    coll.Login = coll.Photo.Substring(iPos + 1).ToLower();
                    iPos = coll.Login.LastIndexOf(".");
                    if (iPos <= 0)
                    {
                        break;
                    }
                    coll.Login = @"oredis-vp\" + coll.Login.Substring(0, iPos);

                    if (strListe.Equals(ListTitles.IlsArriventTitle, StringComparison.CurrentCultureIgnoreCase))
                    {
                        coll.Description = item.GetItemListFieldValueAsText(Fields.TitleField);
                    }
                    if (strListe.Equals(ListTitles.IlsBougentTitle, StringComparison.CurrentCultureIgnoreCase))
                    {
                        coll.Description = item.GetItemListFieldValueAsHtml(Fields.BodyNewsField);
                    }

                    string strGroupeCrt = VPLink2013SPHelper.GetValue(item, "Groupe");
                    if (string.IsNullOrEmpty(strGroupe) && !string.IsNullOrEmpty(strGroupeCrt))
                    {
                        strGroupe = strGroupeCrt;
                    }
                    if (strGroupe == strGroupeCrt)
                    {
                        collaborateurs.Add(coll);
                        if (sbLogins.Length > 0)
                        {
                            sbLogins.Append(",");
                        }
                        sbLogins.Append(FormatStringSql(coll.Login));
                    }
                }
                if (strListe.Equals(ListTitles.IlsPartentTitle, StringComparison.CurrentCultureIgnoreCase))
                {
                    coll.Description = item.GetItemListFieldValueAsText(Fields.TitleField);
                    string strDepart = VPLink2013SPHelper.GetValue(item, "Depart");
                    if (!string.IsNullOrEmpty(strDepart))
                    {
                        coll.Description = strDepart;
                    }

                    string strGroupeCrt = VPLink2013SPHelper.GetValueDate(item, Fields.DatePublicationField);
                    if (string.IsNullOrEmpty(strGroupe) && !string.IsNullOrEmpty(strGroupeCrt))
                    {
                        strGroupe = strGroupeCrt;
                    }
                    if (strGroupe == strGroupeCrt)
                    {
                        collaborateurs.Add(coll);
                    }
                }
            }
        }
    }
}
